package com.ccut.xunfeiSpringboot.controller;

import com.ccut.xunfeiSpringboot.common.AjaxResult;
import com.ccut.xunfeiSpringboot.dto.ChatRequest;
import com.ccut.xunfeiSpringboot.service.BaseService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@RestController
@RequiredArgsConstructor
public class BaseController {

    @Autowired
    private BaseService baseService;

    @PostMapping("/chat")
    public void chat(@RequestBody ChatRequest chatRequest, HttpServletResponse response) throws Exception {
        // 设置响应类型为 text/event-stream 支持流式传输
        response.addHeader("Content-type", "text/event-stream;charset=UTF-8");
        response.addHeader("Cache-Control", "no-cache");
        ServletOutputStream outputStream = response.getOutputStream();

        baseService.chatWithStream(chatRequest, content -> {
            try {
                outputStream.write((content).getBytes());
                outputStream.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
